package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.MemberInfoListMapper;
import cc.rengu.igas.momp.common.dao.impl.MemberInfoListMapperImpl;
import cc.rengu.igas.momp.common.entity.TMMemberInfo;
import cc.rengu.igas.momp.common.enums.QueryTypeEnum;
import cc.rengu.igas.momp.common.enums.RespCodeEnum;
import cc.rengu.igas.momp.facade.bean.MembershipInfoBean;
import cc.rengu.igas.momp.facade.request.QueryMemberInfoRequest;
import cc.rengu.igas.momp.facade.response.QueryMemberInfoResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: liujinan
 * @version: 1.0.0
 * @date 2020/3/26
 * @Description: 会员信息列表查询功能实现
 */
public class MemberInfoQueryService extends RadpService {

    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {
            QueryMemberInfoRequest queryMemberInfoRequest = new QueryMemberInfoRequest();
            ConvertUtil.convertOutput(queryMemberInfoRequest);

            QueryMemberInfoResponse queryMemberInfoResponse = new QueryMemberInfoResponse();
            queryMemberInfoResponse.setHeader(queryMemberInfoRequest.getHeader());
            BizResponse<QueryMemberInfoResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(queryMemberInfoResponse);

            // 服务调用
            BizResponse<QueryMemberInfoResponse> bizResponseNew = memberInfoQuery(xmlTreeUtil, queryMemberInfoRequest, queryMemberInfoResponse);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }

    private BizResponse<QueryMemberInfoResponse> memberInfoQuery(XmlTreeUtil xmlTreeUtil, QueryMemberInfoRequest queryMemberInfoRequest,
                                                                 QueryMemberInfoResponse queryMemberInfoResponse) throws Exception {

        BizResponse<QueryMemberInfoResponse> bizResponse = new BizResponse<>();

        rglog.debug("TXN_NUM = {}", queryMemberInfoRequest.getHeader().getTxnNum());
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(Integer.parseInt(queryMemberInfoRequest.getPageIndex()));
        pageInfo.setPageSize(Integer.parseInt(queryMemberInfoRequest.getPageSize()));
        PageResult pageResult;

        //会员数据查询函数
        pageResult = getAllMemberListInfo(queryMemberInfoRequest, pageInfo);


        List<TMMemberInfo> memberInfoList = new ArrayList<>();
        if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult() || pageResult.getResult().isEmpty()) {
            rglog.info("根据查询条件查询到0条会员信息!");
            queryMemberInfoResponse.setTotalPage(CommonConstant.ZERO_COMMON_CONSTANT);
            queryMemberInfoResponse.setTotalRows(CommonConstant.ZERO_COMMON_CONSTANT);

        } else {
            for (Object object : pageResult.getResult()) {
                memberInfoList.add((TMMemberInfo) object);
            }

            rglog.info("SIZE=<{}>", pageResult.getResult().size());

            List<MembershipInfoBean> membershipInfoBeanList = memberInfoList.stream().map(this::convertMemberInfo).collect(Collectors.toList());
            queryMemberInfoResponse.setMemberInfoList(membershipInfoBeanList);

            queryMemberInfoResponse.setTotalPage(Integer.toString(pageResult.getPageInfo().getTotalPage()));
            queryMemberInfoResponse.setTotalRows(Integer.toString(pageResult.getPageInfo().getTotalRows()));
        }

        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        queryMemberInfoResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        queryMemberInfoResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(queryMemberInfoResponse);

        return bizResponse;
    }

    /**
     * @param queryMemberInfoRequest
     * @return void
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/3/27
     * @Description: 查询会员列表信息
     */
    private PageResult getAllMemberListInfo(QueryMemberInfoRequest queryMemberInfoRequest, PageInfo pageInfo) {

        try {
            String queryType = queryMemberInfoRequest.getQueryType();
            rglog.info("查询类型queryType：" + queryType);
            //如果查询类型不是0：银行人员 4：用户 则无权限查询
            if (!QueryTypeEnum.BANK_QUERY_TYPE.getQueryTypeCode().equals(queryType) &&
                    !QueryTypeEnum.USER_QYERY_TYPE.getQueryTypeCode().equals(queryType)) {
                rglog.error("查询会员信息接口调用上送的字段queryType=<{}>,无查询权限！", queryType);
                throw new BizException(RespCodeEnum.GET_MEMBERINFO_NO_AUTHORITY.getRespCode(), RespCodeEnum.GET_MEMBERINFO_NO_AUTHORITY.getRespDesc());
            }
            //如果是银行人员则不限制memberId,如果是个人赋值memberId
            String memberId = queryMemberInfoRequest.getQueryId();
            if (QueryTypeEnum.BANK_QUERY_TYPE.getQueryTypeCode().equals(queryType)) {
                memberId = null;
            }

            MemberInfoListMapper membInfoListMapper = new MemberInfoListMapperImpl();
            //调用查询函数进行数据查询
            PageResult pageResult = membInfoListMapper.selectMemberInfo(queryMemberInfoRequest.getHeader().getInstId(), memberId,
                    queryMemberInfoRequest.getMobileNo(), queryMemberInfoRequest.getWechatOpenId(),
                    queryMemberInfoRequest.getAlipayUserId(), queryMemberInfoRequest.getCardNo(), pageInfo);

            return pageResult;
        } catch (Exception e) {
            rglog.error("根据查询条件查询会员列表信息失败!");
            throw new BizException(RespCodeEnum.GET_MEMBERINFO_ERROR.getRespCode(), RespCodeEnum.GET_MEMBERINFO_ERROR.getRespDesc());
        }
    }

    /**
     * @param memberInfo
     * @return cc.rengu.igas.momp.facade.bean.MembershipInfoBean
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/3/27
     * @Description: 数据库实体类和接口实体类数据转换
     */
    private MembershipInfoBean convertMemberInfo(TMMemberInfo memberInfo) {
        MembershipInfoBean membershipInfo = new MembershipInfoBean();

        try {
            // 会员ID
            membershipInfo.setMemberId(memberInfo.getMemberId());
            //会员主手机号
            membershipInfo.setMobileNo(memberInfo.getMobileNo());
            //主微信OpenID
            membershipInfo.setWechatOpenId(memberInfo.getWechatOpenId());
            //主支付宝账号
            membershipInfo.setAlipayUserId(memberInfo.getAlipayUserId());
            //主会员卡号
            membershipInfo.setCardNo(memberInfo.getCardNo());
            //性别
            membershipInfo.setGender(memberInfo.getMemberGender());
            //会员生日
            membershipInfo.setBirthday(memberInfo.getMemberBirthday());
            //会员等级
            membershipInfo.setLevel(memberInfo.getMemberLevel());
            //会员创建方式
            membershipInfo.setCreateMethod(memberInfo.getImportMethod());
            //会员创建时间
            membershipInfo.setCreateDate(memberInfo.getImportDate());

        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换会员信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        return membershipInfo;
    }
}
